The range() function is one of the most fundamental and frequently used built-in functions in Python. It generates a sequence of numbers and is primarily used in loops, list comprehensions, and anywhere you need a sequence of integers.
🔑 Key Points:
Built-in function (no import required)
Generates arithmetic sequences of integers
Memory efficient (lazy evaluation)
Immutable sequence type
Commonly used with for loops
2. Definition and Purpose
The range() function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before a specified number. It doesn't actually create a list of numbers in memory but generates them on-demand, making it memory efficient.
📝 Important: In Python 3, range() returns a range object, not a list. In Python 2, range() returned a list, and xrange() returned an iterator (similar to Python 3's range).
Description: The starting number of the sequence. If omitted, starts from 0.
stop (required)
Type: Integer
Default: None
Description: The ending number of the sequence (exclusive). The sequence stops before this number.
step (optional)
Type: Integer
Default: 1
Description: The increment between each number in the sequence. Can be negative.
4. Basic Usage Examples
🚀 Quick Start Examples
# Basic range usage
for i in range( >5):
print(i)
# Converting range to list to see all values
numbers = list( range( >5))
print(numbers)
# Using range in list comprehension
squares = [x** >2 for x in range( >5)]
print(squares)
0 1 2 3 4
[0, 1, 2, 3, 4]
[0, 1, 4, 9, 16]
5. Single Parameter Range
When you provide only one argument to range(), it represents the stop value. The sequence starts from 0 and goes up to (but not including) the stop value.
Function Call
Generated Sequence
Description
range(0)
Empty sequence
No numbers generated
range(1)
[0]
Single number: 0
range(5)
[0, 1, 2, 3, 4]
Numbers from 0 to 4
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Numbers from 0 to 9
Single Parameter Examples
# Counting from 0 to n-1
print( "Counting to 3:")
for i in range( >3):
print( f"Count: {i}")
# Creating a list of indices
my_list = [ 'apple', 'banana', 'cherry']
for index in range( len(my_list)):
print( f"Index {index}: {my_list[index]}")
When you provide two arguments, the first is the start value and the second is the stop value. The sequence begins at start and goes up to (but not including) stop.
Function Call
Generated Sequence
Description
range(1, 5)
[1, 2, 3, 4]
From 1 to 4
range(5, 10)
[5, 6, 7, 8, 9]
From 5 to 9
range(-3, 3)
[-3, -2, -1, 0, 1, 2]
From -3 to 2
range(10, 5)
Empty sequence
Start > Stop with positive step
Two Parameters Examples
# Custom start and stop
print( "Numbers from 3 to 7:")
for num in range( >3, >8):
print(num)
# Working with negative numbers
negative_range = list( range(- >5, >1))
print( f"Negative to positive: {negative_range}")
# Year range example
print( "Years from 2020 to 2024:")
for year in range( >2020, >2025):
print(year)
7. Three Parameters Range
When you provide three arguments, you specify start, stop, and step. The step determines the increment between consecutive numbers.
# Range is still iterable
print( "First 10 elements from range:")
for i, value in enumerate(range_obj):
if i >= >10:
break
print(value, end= " ")
12. Practical Examples
Example 1: Multiplication Table
def multiplication_table(number, limit= >10):
"""Generate multiplication table for a number"""
print( f"Multiplication table for {number}:")
for i in range( >1, limit + >1):
result = number * i
print( f"{number} × {i} = {result}")
# Generate table for 7
multiplication_table( >7, >5)
Example 2: Password Generator
import random
import string
def generate_password(length= >8):
"""Generate a random password"""
characters = string.ascii_letters + string.digits + "!@#$%^&*"
password = ""
for _ in range(length):
password += random.choice(characters)
return password
# Generate 5 passwords
print( "Generated passwords:")
for i in range( >5):
password = generate_password( >12)
print( f"Password {i+1}: {password}")
Example 3: Grade Calculator
def calculate_grades(scores):
"""Calculate letter grades for a list of scores"""
grades = []
for i in range( len(scores)):
score = scores[i]
if score >= >90:
grade = 'A'
elif score >= >80:
grade = 'B'
elif score >= >70:
grade = 'C'
elif score >= >60:
grade = 'D'
else:
grade = 'F'
# Using range instead of enumerate
fruits = [ 'apple', 'banana', 'cherry', 'date']
# Method 1: Using enumerate (preferred)
print( "Using enumerate:")
for index, fruit in enumerate(fruits):
print( f"{index}: {fruit}")
# Method 2: Using range
print( "Using range:")
for i in range( len(fruits)):
print( f"{i}: {fruits[i]}")
Pattern 2: Matrix Operations
# Creating and working with 2D matrices
rows, cols = >3, >4
# Create matrix using nested loops with range
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(i * cols + j + >1)
matrix.append(row)
# Print matrix
print( "Matrix:")
for i in range(rows):
for j in range(cols):
print( f"{matrix[i][j]:3}", end= " ")
print() # New line after each row
Pattern 3: Batch Processing
def process_in_batches(data, batch_size):
"""Process data in batches"""
for i in range( >0, len(data), batch_size):
batch = data[i:i + batch_size]
print( f"Processing batch {i//batch_size + 1}: {batch}")
# Process batch here
Prefer enumerate() when you need both index and value
Use range() for memory-efficient large sequences
Convert to list only when necessary
Use meaningful variable names in range loops
❌ Don'ts:
Don't use range(len()) when enumerate() is better
Don't convert large ranges to lists unnecessarily
Don't use range() for iterating over sequences directly
Don't forget that range() is exclusive of the stop value
Don't use step=0 (causes ValueError)
Best Practice Examples
# ✅ Good: Using enumerate for index and value
items = [ 'apple', 'banana', 'cherry']
for index, item in enumerate(items):
print( f"{index}: {item}")
# ❌ Less ideal: Using range(len())
for i in range( len(items)):
print( f"{i}: {items[i]}")
# ✅ Good: Direct iteration when index not needed
for item in items:
print(item)
# ✅ Good: Using range for mathematical sequences
fibonacci = [ >0, >1]
for i in range( >2, >10):
fibonacci.append(fibonacci[i- >1] + fibonacci[i- >2])
print( f"Fibonacci: {fibonacci}")
15. Common Errors and Solutions
Error
Cause
Solution
Example
ValueError: step argument must not be zero
Using step=0
Use non-zero step value
range(0, 10, 1) instead of range(0, 10, 0)
Empty range
start ≥ stop with positive step
Check start/stop values or use negative step
range(10, 0, -1) for countdown
TypeError: 'range' object is not subscriptable
Trying to slice range in Python 2
Convert to list first or use Python 3
list(range(10))[2:5]
OverflowError
Range values too large
Use smaller values or different approach
Consider itertools for very large ranges
Error Handling Examples
# Handling potential errors
def safe_range(start, stop, step= >1):
"""Create a range with error checking"""
try:
if step == >0:
raise ValueError( "Step cannot be zero")
r = range(start, stop, step)
if len(r) == >0:
print( f"Warning: Empty range({start}, {stop}, {step})")
return r
except ValueError as e:
print( f"Error: {e}")
return range( >0) # Return empty range